package com.gitee.fsadmin.config;

import com.gitee.fastmybatis.core.util.StringUtil;
import com.gitee.fsadmin.common.util.SystemUtil;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.serialization.jackson.JacksonActionExecutor;
import org.noear.solon.serialization.jackson.JacksonRenderFactory;
import org.noear.solon.web.staticfiles.StaticMappings;
import org.noear.solon.web.staticfiles.repository.FileStaticRepository;

import javax.sql.DataSource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author 六如
 */
@Configuration
@Slf4j
public class FmAdminConfiguration {

    @Inject("${front-location:}")
    private String frontLocation;

    //此下的 db1 与 mybatis.db1 将对应在起来 //可以用 @Db("db1") 注入mapper
    //typed=true，表示默认数据源。@Db 可不带名字注入
    @Bean(name = "db1", typed = true)
    public DataSource db1(@Inject("${dataSource.db1}") HikariDataSource ds) {
        log.info("dataSource.db1.db={}", ds.getSchema());
        log.info("dataSource.db1.username={}", ds.getUsername());
        log.info("dataSource.db1.jdbcUrl={}", ds.getJdbcUrl());
        return ds;
    }


    @Bean
    public void jsonInit(@Inject JacksonRenderFactory factory, @Inject JacksonActionExecutor executor) {
        //方式1：通过转换器，做简单类型的定制
        factory.addConvertor(Date.class, s -> s.getTime());

        factory.addConvertor(LocalDate.class, s -> s.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        factory.addConvertor(BigDecimal.class, s -> s.toPlainString());

        //方式2：通过编码器，做复杂类型的原生定制（基于框架原生接口）
        /*factory.addEncoder(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date date, JsonGenerator out, SerializerProvider sp) throws IOException {
                out.writeNumber(date.getTime());
            }
        });*/
    }

    /**
     * 初始化静态资源文件
     */
    @Init
    public void initStaticFile() {
        String frontRoot;
        if (StringUtils.isNotBlank(frontLocation)) {
            frontRoot = StringUtil.trimTrailingCharacter(frontLocation, '/');
        } else {
            String homeDir = SystemUtil.getUserDir();
            if ("/".equals(homeDir)) {
                homeDir = "";
            }
            frontRoot = homeDir + "/dist";
        }
        log.info("前端资源目录：{}", frontRoot);

        StaticMappings.add("/", new FileStaticRepository(frontRoot));
    }

}
